/**
 * 地图引擎核心模块
 * @description 负责Mars3D地图实例的创建、初始化和生命周期管理
 */
import * as mars3d from 'mars3d';

import { ref, nextTick } from 'vue';
import {
  DEFAULT_MAP_VIEWS,
  MAP_CONFIG,
  CONTROL_CONFIG,
  TERRAIN_CONFIG
} from '../constants.js';

/**
 * 地图引擎核心类
 * @class MapEngine
 */
export class MapEngine {
  constructor(options = {}) {
    this.map = null;
    this.mapId = options.mapId || 'mapContainer';
    this.options = options;
    this.initialized = false;
    this.destroyed = false;

    // 事件系统
    this.events = new Map();

    // 性能监控
    this.performance = {
      initTime: 0,
      renderTime: 0,
      layerCount: 0
    };
  }

  /**
   * 初始化地图引擎
   * @param {Object} config - 地图配置
   * @returns {Promise<mars3d.Map>} 地图实例
   */
  async initialize(config = {}) {
    if (this.initialized) {
      console.warn('MapEngine already initialized');
      return this.map;
    }

    const startTime = performance.now();

    try {
      // 合并配置
      const mapConfig = this._buildMapConfig(config);

      // 等待DOM就绪
      await nextTick();

      // 创建地图实例
      this.map = new mars3d.Map(this.mapId, mapConfig);

      // 设置初始化标志
      this.initialized = true;

      // 绑定事件监听器
      this._bindEvents();

      // 记录性能指标
      this.performance.initTime = performance.now() - startTime;

      // 触发初始化完成事件
      this.emit('initialized', this.map);

      console.log(`MapEngine initialized in ${this.performance.initTime.toFixed(2)}ms`);
      return this.map;

    } catch (error) {
      console.error('MapEngine initialization failed:', error);
      throw error;
    }
  }

  /**
   * 构建地图配置
   * @private
   * @param {Object} config - 用户配置
   * @returns {Object} 完整的地图配置
   */
  _buildMapConfig(config) {
    const {
      jiaodu = 1,
      showActions = true,
      animation = true,
      enableTerrain = true,
      mapType = 'offline',
      baseMapType = 'img',
      showAnnotation = true,
      tdtToken = '6c99c7793f41fccc4bd595b03711913e'
    } = { ...this.options, ...config };

    // 创建场景中心配置
    const sceneCenter = jiaodu === 1
      ? DEFAULT_MAP_VIEWS.angle1
      : DEFAULT_MAP_VIEWS.angle2;

    // 创建动画配置
    const animationConfig = animation
      ? {}
      : MAP_CONFIG.animationConfig;

    // 创建控件配置
    const controlConfig = {
      ...CONTROL_CONFIG,
      baseLayerPicker: false,
      homeButton: showActions,
      sceneModePicker: showActions,
      navigationHelpButton: showActions,
      fullscreenButton: showActions,
      zoom: showActions
    };

    // 创建地形配置
    const terrainConfig = enableTerrain ? TERRAIN_CONFIG : {};

    // 根据地图类型配置底图
    let basemaps = [];
    if (mapType === 'online') {
      // 在线天地图配置，参考官方示例
      const tdtBaseLayer = {
        name: `天地图${baseMapType}底图`,
        type: 'tdt',
        layer: `${baseMapType}_d`,
        key: [tdtToken],
        show: true,
        isInitial: true
      };

      basemaps.push(tdtBaseLayer);

      // 添加注记层
      if (showAnnotation) {
        const tdtAnnotationLayer = {
          name: `天地图${baseMapType}注记`,
          type: 'tdt',
          layer: `${baseMapType}_z`,
          key: [tdtToken],
          show: true,
          isInitial: true
        };
        basemaps.push(tdtAnnotationLayer);
      }
    }
    // 离线地图不在这里配置，保持原有的LayerManager逻辑

    return {
      scene: {
        center: sceneCenter,
        ...MAP_CONFIG.scene,
        cameraController: {
          ...MAP_CONFIG.cameraController,
          ...animationConfig
        }
      },
      control: controlConfig,
      terrain: terrainConfig,
      basemaps: basemaps,
      // 性能优化配置
      contextOptions: {
        requestWebgl2: true,
        powerPreference: 'high-performance'
      }
    };
  }


  /**
   * 绑定地图事件
   * @private
   */
  _bindEvents() {
    if (!this.map) return;

    // 地图加载完成
    this.map.on(mars3d.EventType.load, () => {
      this.emit('loaded');
    });

    // 相机移动事件
    this.map.on(mars3d.EventType.cameraChanged, (event) => {
      this.emit('cameraChanged', event);
    });

    // 点击事件
    this.map.on(mars3d.EventType.click, (event) => {
      this.emit('click', event);
    });

    // 右键事件
    this.map.on(mars3d.EventType.rightClick, (event) => {
      this.emit('rightClick', event);
    });

    // 鼠标移动事件
    this.map.on(mars3d.EventType.mouseMove, (event) => {
      this.emit('mouseMove', event);
    });

    // 图层添加事件
    this.map.on(mars3d.EventType.addLayer, (event) => {
      this.performance.layerCount++;
      this.emit('layerAdded', event);
    });

    // 图层移除事件
    this.map.on(mars3d.EventType.removeLayer, (event) => {
      this.performance.layerCount--;
      this.emit('layerRemoved', event);
    });
  }

  /**
   * 获取地图实例
   * @returns {mars3d.Map|null} 地图实例
   */
  getInstance() {
    return this.map;
  }

  /**
   * 检查是否已初始化
   * @returns {boolean} 是否已初始化
   */
  isInitialized() {
    return this.initialized && !this.destroyed;
  }

  /**
   * 获取地图状态信息
   * @returns {Object} 状态信息
   */
  getStatus() {
    return {
      initialized: this.initialized,
      destroyed: this.destroyed,
      performance: { ...this.performance },
      layerCount: this.map ? this.map.layerManager.layers.length : 0,
      camera: this.map ? this._getCameraInfo() : null
    };
  }

  /**
   * 获取相机信息
   * @private
   * @returns {Object} 相机信息
   */
  _getCameraInfo() {
    if (!this.map) return null;

    const camera = this.map.camera;
    const cartographic = mars3d.Cartographic.fromCartesian(camera.position);

    return {
      lng: mars3d.Math.toDegrees(cartographic.longitude),
      lat: mars3d.Math.toDegrees(cartographic.latitude),
      alt: cartographic.height,
      heading: mars3d.Math.toDegrees(camera.heading),
      pitch: mars3d.Math.toDegrees(camera.pitch),
      roll: mars3d.Math.toDegrees(camera.roll)
    };
  }

  /**
   * 重置地图到初始状态
   * @param {Object} options - 重置选项
   */
  reset(options = {}) {
    if (!this.map) return;

    const {
      clearLayers = true,
      resetCamera = true,
      duration = 1.0
    } = options;

    // 清除图层
    if (clearLayers) {
      this.map.layerManager.layers.forEach(layer => {
        if (layer.type !== 'xyz') { // 保留底图
          this.map.removeLayer(layer, true);
        }
      });
    }

    // 重置相机
    if (resetCamera) {
      const resetView = this.options.jiaodu === 1
        ? DEFAULT_MAP_VIEWS.angle1
        : DEFAULT_MAP_VIEWS.angle2;

      this.map.centerAt(resetView, { duration });
    }

    this.emit('reset');
  }

  /**
   * 销毁地图引擎
   */
  destroy() {
    if (this.destroyed) return;

    try {
      // 清理事件监听器
      this.events.clear();

      // 销毁地图实例
      if (this.map) {
        this.map.destroy();
        this.map = null;
      }

      // 设置销毁标志
      this.destroyed = true;
      this.initialized = false;

      console.log('MapEngine destroyed');

    } catch (error) {
      console.error('Error destroying MapEngine:', error);
    }
  }

  /**
   * 事件系统 - 注册事件监听器
   * @param {string} event - 事件名称
   * @param {Function} callback - 回调函数
   */
  on(event, callback) {
    if (!this.events.has(event)) {
      this.events.set(event, []);
    }
    this.events.get(event).push(callback);
  }

  /**
   * 事件系统 - 移除事件监听器
   * @param {string} event - 事件名称
   * @param {Function} callback - 回调函数
   */
  off(event, callback) {
    if (!this.events.has(event)) return;

    const callbacks = this.events.get(event);
    const index = callbacks.indexOf(callback);
    if (index > -1) {
      callbacks.splice(index, 1);
    }
  }

  /**
   * 事件系统 - 触发事件
   * @param {string} event - 事件名称
   * @param {...any} args - 事件参数
   */
  emit(event, ...args) {
    if (!this.events.has(event)) return;

    this.events.get(event).forEach(callback => {
      try {
        callback(...args);
      } catch (error) {
        console.error(`Error in event callback for ${event}:`, error);
      }
    });
  }
}

/**
 * 地图引擎组合函数
 * @param {Object} options - 配置选项
 * @returns {Object} 地图引擎API
 */
export function useMapEngine(options = {}) {
  const engine = ref(null);
  const map = ref(null);

  /**
   * 初始化地图引擎
   * @param {Object} config - 初始化配置
   */
  const initEngine = async (config = {}) => {
    try {
      engine.value = new MapEngine(options);
      map.value = await engine.value.initialize(config);
      return map.value;
    } catch (error) {
      console.error('Failed to initialize map engine:', error);
      throw error;
    }
  };

  /**
   * 获取地图实例
   */
  const getMapInstance = () => map.value;

  /**
   * 获取引擎实例
   */
  const getEngine = () => engine.value;

  /**
   * 销毁引擎
   */
  const destroy = () => {
    if (engine.value) {
      engine.value.destroy();
      engine.value = null;
      map.value = null;
    }
  };

  return {
    engine,
    map,
    initEngine,
    getMapInstance,
    getEngine,
    destroy
  };
}
